import cv2
import os
import re

# 图片目录路径
image_folder = '/home/JSDC/017254/code/gitee/map_learing/04_map_grid_cxx/CXX/build'  # 替换为你的图片目录路径
output_video = 'cxx_ai_video.mp4'  # 输出视频文件名

# 获取目录中的所有图片文件
images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]

# 按文件名中的数字排序
def extract_number(filename):
    match = re.search(r'(\d+)', filename)  # 提取文件名中的数字部分
    return int(match.group(1)) if match else 0

images.sort(key=extract_number)

# 检查是否有图片
if not images:
    print("目录中没有找到图片")
    exit()

# 获取第一张图片的尺寸
first_image_path = os.path.join(image_folder, images[0])
frame = cv2.imread(first_image_path)
height, width, layers = frame.shape

# 定义视频编码器和输出视频
fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 使用 mp4 编码
video = cv2.VideoWriter(output_video, fourcc, 10, (width, height))  # 30 为帧率

# 遍历图片并写入视频
for image in images:
    image_path = os.path.join(image_folder, image)
    frame = cv2.imread(image_path)
    video.write(frame)

# 释放视频对象
video.release()
print(f"视频已保存为 {output_video}")
